import 'dart:async';

import 'package:gold/base/view_model.dart';
import 'package:gold/http/api_order.dart';
import 'package:gold/http/http.dart';
import 'package:gold/model/refund_model.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';

/// @description: 退款页面
/// @author tangzhentao
/// @created at 22:49 2025/2/27

class RefundViewmodel extends Viewmodel {
  /// 订单id
  final int _orderId;

  /// 计时器
  Timer? _timer;

  int _minutes = 0;
  /// 倒计时
  int get minutes => _minutes;
  set minutes(int value) {
    if (_minutes != value) {
      _minutes = value;
      notifyListeners();
    }
  }

  /// 售后详情
  RefundModel? detail;

  RefundViewmodel(this._orderId);

  /// 加载售后详情
  Future load() async {
    setLoading();
    final result = await Http().request<RefundModel>(ApiOrder.refundDetail, data: {'order_id': _orderId}, showErrorMsg: false);
    if (result.success) {
      detail = result.data;
      if (detail != null) {
        _startTimer();
        setSuccess();
      } else {
        setEmpty(msg: '暂无售后信息');
      }
    } else {
      setFailed(msg: result.msg);
    }
  }

  /// 开启计时器
  void _startTimer() {
    final createDate = DateTime.tryParse(detail?.createdAt?? '');
    if (createDate != null) {
      final countMinutes = ((DateTime.now().millisecondsSinceEpoch - createDate.millisecondsSinceEpoch) / (1000 * 60)).toInt();
      if (countMinutes <= 3 * 24 * 60) {
        _minutes = countMinutes;
        _timer = Timer.periodic(const Duration(minutes: 1), (_) {
          minutes--;
          if (_minutes == 0) {
            _cancelTimer();
          }
        });
      }
    }
  }

  /// 停止计时器
  void _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }

  /// 去退款详情页
  void toDetailPage(String refund) {
    XfgNav.pushNamed(Routes.myOrderRefundApplyingDetail, arguments: {'refund': refund, 'logs': detail?.logs?? []});
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }
}
